package com.lvsc.sdaplacefinder;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;

import com.lvsc.sdaplacefinder.adapter.ImageAdapter;
import com.lvsc.sdaplacefinder.models.ImageToUpload;
import com.lvsc.sdaplacefinder.models.Place;
import com.lvsc.sdaplacefinder.service.ImageUploaderTask;

public class ImagePlace extends Activity {

	protected static final String LOG_TAG = ImagePlace.class.getName();
	private List<ImageToUpload> bitmaps;
	private Bitmap mImageBitmap;
	protected static final int ACTION_IMAGE_CAPTURE = 0;
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private String mCurrentPhotoPath;
	private GridView listPhoto;
	private ImageAdapter adapter;
	private Place place;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.photo);

		Bundle data = getIntent().getExtras();

		place = (Place) data.getSerializable("place");

		setTitle(place.getName());

		listPhoto = (GridView) findViewById(R.id.horizontalListlView1);
		bitmaps = new ArrayList<ImageToUpload>();
		adapter = new ImageAdapter(this, bitmaps);
		listPhoto.setAdapter(adapter);
	}

	public void onClickDone(View v) {
		upload();
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case ACTION_IMAGE_CAPTURE:

			if (resultCode == RESULT_OK) {
				handleSmallCameraPhoto(data);
			}

			break;
		}
	}

	private void handleSmallCameraPhoto(Intent intent) {

		Bundle extras = intent.getExtras();
		mImageBitmap = (Bitmap) extras.get("data");
		bitmaps.add(new ImageToUpload(mCurrentPhotoPath, mImageBitmap));
		adapter.notifyDataSetChanged();

	}

	private void dispatchTakePictureIntent(int actionCode) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(takePictureIntent, actionCode);
		switch (actionCode) {
		case ACTION_IMAGE_CAPTURE:
			File f = null;

			try {
				f = createImageFile();
				mCurrentPhotoPath = f.getAbsolutePath();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(f));
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(LOG_TAG, "IOException", e);
				f = null;
				mCurrentPhotoPath = null;
			}
			break;

		default:
			break;
		}

	}

	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					getAlbumName());

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	private String getAlbumName() {
		return getString(R.string.album_name);
	}

	public void upload() {
		if (mCurrentPhotoPath != null) {
			new ImageUploaderTask(bitmaps, place.getId()).execute();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_create, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.newPicture:
			dispatchTakePictureIntent(ACTION_IMAGE_CAPTURE);
		}

		return super.onOptionsItemSelected(item);
	}
}
